//
//  AllViewController.m
//  万词王
//
//  Created by rimi on 2016/11/29.
//  Copyright © 2016年 dongfumei. All rights reserved.
//

#import "AllViewController.h"
#import "AllViewModel.h"
#import "NetworkRequestManager.h"

#import "SearchModel.h"

@interface AllViewController () <UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>{
    id _oberver;
}

@property (nonatomic, strong) AllViewModel *viewModel;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UITextField *searchField;
@property (nonatomic, strong) NSArray *dataSource;
@property (nonatomic, strong) NSArray *ciArray;
@property (nonatomic, strong) NSArray *ziArray;
@property (nonatomic, strong) NSMutableArray <SearchModel *>*allArray;

@end

@implementation AllViewController

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:_oberver];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor orangeColor];
    
    
    _oberver = [[NSNotificationCenter defaultCenter] addObserverForName:UITextFieldTextDidChangeNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
       
    }];
    
    [self initializeAppearence];
}

-(void)initializeAppearence{
    
    [self.navigationBars addSubview:self.searchField];
    [self.view addSubview:self.tableView];
//    [self.viewModel getData];
//    [self.viewModel addObserver:self forKeyPath:[self.viewModel oberString] options:NSKeyValueObservingOptionNew context:nil];
}



- (AllViewModel *)viewModel {
    
    if (!_viewModel) {
        
        _viewModel = [[AllViewModel alloc] init];
    }
    return _viewModel;
}

- (void)initalizeDataSource:(NSString *)str {
    
    _allArray = [NSMutableArray array];

    
    NSString *url=@"http://api.avatardata.cn/ChengYu/Search";
    NSLog(@"%@", self.searchField.text);
    NSDictionary *dic=@{@"key":@"55599b7297024aa4af0d75a009c5dedc",@"keyWord":str};
    
    AFHTTPSessionManager   *manager=[AFHTTPSessionManager manager];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/html",@"text/javascript", nil];
    
    [manager GET:url parameters:dic progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"%@",responseObject);
        
        NSArray *idiomModels = [IdiomModel modelsWithArray:responseObject[@"result"]];
        
        if (idiomModels.count > 0) {
            [_allArray addObjectsFromArray:idiomModels];
        }
        
            NSString *url = @"http://api.avatardata.cn/CiHai/Query";
        NSDictionary *dic = @{@"key":@"8a2b87ac4d6c4d9898144fc0aa882a58",@"keyword":str};
        [NetworkRequestManager getMethod:url withParames:dic Success:^(id respondObject) {
            NSLog(@"%@",respondObject);
            NSArray *wordModels = [SingleWordModel modelsWithArray:respondObject[@"result"]];
            if (wordModels.count > 0) {
                [_allArray addObjectsFromArray:wordModels];
            }
            
            NSString *url = @"http://api.avatardata.cn/XinHuaZiDian/LookUp";
            NSDictionary *dic = @{@"key":@"0ec3c921d7b749e3b5feffc5190555b1",@"content":str};
            [NetworkRequestManager getMethod:url withParames:dic Success:^(id respondObject) {
                NSArray *singleModels = [WordModel modelsWithArray:respondObject[@"result"]];
                
                if (singleModels.count > 0) {
                    [_allArray addObjectsFromArray:singleModels];
                }
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.tableView reloadData];
                });
                
                
            } Failure:^(NSError *error) {
                
            }];

        } Failure:^(NSError *error) {
            
        }];
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self.tableView reloadData];
//        });

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error.localizedDescription);
    }];
}

#pragma mark -  UITextFieldDelegate;
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{

     [self initalizeDataSource:self.searchField.text];
    
    [self.searchField resignFirstResponder];
    return YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _allArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static  NSString  *string=@"SerUITableViewCell";
    UITableViewCell  *cell=[tableView dequeueReusableCellWithIdentifier:string];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:string];
    }
    
    
    NSLog(@"%@", self.allArray[indexPath.row].content);
    cell.textLabel.text = self.allArray[indexPath.row].content;
    
    return cell;
    
}


#pragma mark - setter与getter
- (UITextField *)searchField
{
    if (!_searchField) {
        _searchField=[[UITextField alloc]initWithFrame:CGRectMake(60, 15, 414-80, 40)];
        _searchField.delegate=self;
        _searchField.backgroundColor=[UIColor groupTableViewBackgroundColor];
        _searchField.layer.cornerRadius=10;
        _searchField.placeholder=@"请输入要查找的文字";
        [_searchField canBecomeFirstResponder];
        _searchField.font=[UIFont systemFontOfSize:15];
        _searchField.autocapitalizationType=UITextAutocapitalizationTypeNone;;
        _searchField.clearButtonMode=UITextFieldViewModeWhileEditing;
        _searchField.returnKeyType=UIReturnKeySearch;
        
    }
    return _searchField;
}

- (UITableView *)tableView{
    
    if (!_tableView) {
        _tableView=[[UITableView alloc]initWithFrame:AAdaptionRect(0, 64, kWidth, kHeight - 64) style:UITableViewStylePlain];
        _tableView.dataSource=self;
        _tableView.delegate=self;
    }
    return _tableView;
}


@end
